import * as http from '@/http'
let baseUrl = 'http://wx.xlink.cn'
let XLINKAPPID = '2e0fa6b2324c8400'// 云智易微信应用appID ,非微信appID
let unsubscribeUrl = 'http://api2.xlink.cn'
// let baseUrl = 'http://139.196.164.250'
// let XLINKAPPID = '2e07d2b0b45aaa00'// 云智易微信应用appID ,非微信appID

// 获取url的code参数
function getSearchCode () {
  let search = location.href
  let searchs = {}
  let strs
  if (search.indexOf('?') !== -1) {
    search = search.substr(search.indexOf('?') + 1)
    strs = search.split('&')
    for (let i = 0; i < strs.length; i++) {
      searchs[strs[i].split('=')[0]] = decodeURIComponent(strs[i].split('=')[1])
    }
  }
  return searchs['code']
}

export default {
  // jssdk
  jssdk (timestamp, url, NONCESTR) {
    return http.get(`${baseUrl}/v2/wechat_gateway/${XLINKAPPID}/url_signature?nonceStr=${NONCESTR}&timestamp=${timestamp}&url=${url}`)
  },
  /**
   * 微信登录认证
   * 认证登录获得RESTful调用凭证，通过调用凭证可调用企业信息管理接口，获取openId
   */
  getOpenId () {
    let code = getSearchCode()
    return http.get(`${baseUrl}/v2/wechat_gateway/${XLINKAPPID}/get_open_id?code=${code}`)
  },

  // 获取tooken
  getUserAuthorize (OPENID) {
    return http.get(`${baseUrl}/v2/wechat_gateway/${XLINKAPPID}/wx_access_token?open_id=${OPENID}&resource=wechat`)
  },

  // 获取用户绑定设备列表
  getDeviceList () {
    return http.get(`${baseUrl}/v2/wechat_gateway/${XLINKAPPID}/wx_device_list?access_token=XLINKUserAccessToken&open_id=${window.localStorage.getItem('openId')}`)
  },

  // 个人中心
  getUserInfo () {
    return http.get(`${baseUrl}/v2/wechat_gateway/${XLINKAPPID}/wx_user_info?access_token=XLINKUserAccessToken&open_id=${window.localStorage.getItem('openId')}`)
  },
  // 获取绑定设备的信息
  getDeviceDetail (DEVICEID) {
    return http.get(`${baseUrl}/v2/wechat_gateway/${XLINKAPPID}/device_info?open_id=${window.localStorage.getItem('openId')}&device_id=${DEVICEID}`)
  },
  // 修改设备名称
  changeDeviceName (DEVICEID, params) {
    return http.post(`${baseUrl}/v2/wechat_gateway/${XLINKAPPID}/device_info?open_id=${window.localStorage.getItem('openId')}&device_id=${DEVICEID}`, params)
  },
  // 取消绑定设备 还需要取消订阅设备否则微信内依然会接受推送
  unbindingDevice (DEVICEID, TICKET) {
    return http.get(`${baseUrl}/v2/wechat_gateway/${XLINKAPPID}/wx_device_unbind?access_token=XLINKUserAccessToken&open_id=${window.localStorage.getItem('openId')}&device_id=${DEVICEID}&ticket=${TICKET}`)
  },
  // 取消订阅设备
  unsubscribe (USERID, params) {
    return http.post(`${unsubscribeUrl}/v2/user/${USERID}/unsubscribe`, params)
  }
}
